package T02_查询封装对象practice;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;


/**
 *练习
 *  *查询 user表的数据将其封装为对象然后打印
 *       1.定义Emp类
 *       2.定义方法 public List<Emp> findAll(){}
 *       3.实现方法 select * from  user
 *  *定义一个方法,查询user表的数据将其封装为对象,然后装载集合返回
 */
public class DomeTest01 {


    public static void main(String[] args) {
        List<User> userList=new DomeTest01().findAll();
        userList.forEach((v)->{
            System.out.println(v.toString());
        });
    }
    /**
     * 查询所有User对象
     * @return
     */
    public List<User> findAll(){
        Connection conn=null;
        Statement statement=null;
        ResultSet rs=null;
        List<User> list=null;
        try {
            //1.注册驱动----向下兼容
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
             conn = DriverManager.getConnection("jdbc:mysql://localhost:3309/test??useSSL=false", "root", "root");
            //3.定义sql
            String sql="select * from  user";
            //4.获取执行sql的对象
             statement=conn.createStatement();
            //5.执行sql
             rs = statement.executeQuery(sql);
            //6.遍历结果集,封装对象,装载集合
            User user=null;
            list=new ArrayList();
            while (rs.next()){
                //获取数据
                int id=rs.getInt("id");
                String name=rs.getString("name");
                String password=rs.getString("password");
                String address=rs.getString("address");
                String phone=rs.getString("phone");
                //创建emp对象
                user=new User(id,name,password,address,phone);
                //装载集合
                list.add(user);

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return  list;
   }
}
